/**
 * 菜单配置模块
 * 集中管理所有菜单项的配置数据，便于维护和扩展
 */

/**
 * 创建菜单项工厂函数
 * @param {Function} getFormattedKeyMapEntry - 获取快捷键的函数
 * @param {Object} handlers - 菜单项点击处理函数集合
 * @returns {Object} 菜单项配置对象
 */
function createMenuConfig (getFormattedKeyMapEntry, handlers) {
  const {
    sendIPCToWindow,
    createWindow,
    showFocusModeDialog1,
    showFocusModeDialog2,
    openTabInWindow,
    isFocusMode,
    windows,
    settings,
    app,
    webContents,
    getWindowWebContents,
    destroyAllViews,
    placesWindow,
    electron,
    isDevelopmentMode,
    isDebuggingEnabled,
    isHarmonyOSPlatform
  } = handlers

  /**
   * 创建带事件处理的菜单项
   */
  function createMenuItem (config) {
    const item = {
      label: config.label,
      accelerator: config.accelerator,
      role: config.role,
      type: config.type,
      checked: config.checked,
      visible: config.visible,
      submenu: config.submenu
    }

    if (config.click) {
      item.click = function (menuItem, window, event) {
        // 键盘快捷键已在渲染进程中处理，避免重复触发
        if (event && event.triggeredByAccelerator && config.skipAccelerator) {
          return
        }
        config.click(menuItem, window, event)
      }
    }

    return item
  }

  /**
   * 标签页和任务相关操作
   */
  const tabTaskActions = [
    {
      label: l('appMenuNewTab'),
      accelerator: getFormattedKeyMapEntry('addTab'),
      click: (item, window, event) => {
        if (!event || !event.triggeredByAccelerator) {
          sendIPCToWindow(window, 'addTab')
        }
      },
      skipAccelerator: true
    },
    {
      label: l('appMenuNewPrivateTab'),
      accelerator: getFormattedKeyMapEntry('addPrivateTab'),
      click: (item, window, event) => {
        if (!event || !event.triggeredByAccelerator) {
          sendIPCToWindow(window, 'addPrivateTab')
        }
      },
      skipAccelerator: true
    },
    {
      label: l('appMenuNewTask'),
      accelerator: getFormattedKeyMapEntry('addTask'),
      click: (item, window, event) => {
        if (!event || !event.triggeredByAccelerator) {
          sendIPCToWindow(window, 'addTask')
        }
      },
      skipAccelerator: true
    }
    // 检测是否为鸿蒙平台，如果是则隐藏"新窗口"菜单项
    // ...(isHarmonyOSPlatform ? [] : [
    //   {
    //     label: l('appMenuNewWindow'),
    //     accelerator: getFormattedKeyMapEntry('addWindow'),
    //     click: () => {
    //       if (isFocusMode) {
    //         showFocusModeDialog2()
    //       } else {
    //         createWindow()
    //       }
    //     }
    //   }
    // ])
  ]

  // 检测是否为鸿蒙平台，如果是则隐藏"新窗口"菜单项
  if (isHarmonyOSPlatform && isHarmonyOSPlatform()) {
    // 鸿蒙平台：隐藏"新窗口"菜单项
    console.log('鸿蒙平台：已隐藏"新窗口"菜单项')
  } else {
    // 非鸿蒙平台：添加"新窗口"菜单项
    tabTaskActions.push({
      label: l('appMenuNewWindow'),
      accelerator: getFormattedKeyMapEntry('addWindow'),
      click: () => {
        if (isFocusMode) {
          showFocusModeDialog2()
        } else {
          createWindow()
        }
      }
    })
  }

  /**
   * 个人数据相关操作
   */
  const personalDataItems = [
    {
      label: l('appMenuBookmarks'),
      accelerator: getFormattedKeyMapEntry('showBookmarks'),
      click: (item, window, event) => {
        if (!event || !event.triggeredByAccelerator) {
          sendIPCToWindow(window, 'showBookmarks')
        }
      },
      skipAccelerator: true
    },
    {
      label: l('appMenuHistory'),
      accelerator: getFormattedKeyMapEntry('showHistory'),
      click: (item, window, event) => {
        if (!event || !event.triggeredByAccelerator) {
          sendIPCToWindow(window, 'showHistory')
        }
      },
      skipAccelerator: true
    }
  ]

  /**
   * 退出操作
   */
  const quitAction = {
    label: l('appMenuQuit').replace('%n', app.name),
    accelerator: getFormattedKeyMapEntry('quitMin'),
    click: (item, window, event) => {
      if (!event || !event.triggeredByAccelerator) {
        app.quit()
      }
    }
  }

  /**
   * 偏好设置操作
   */
  const preferencesAction = {
    label: l('appMenuPreferences'),
    accelerator: 'CmdOrCtrl+,',
    click: (item, window) => {
      sendIPCToWindow(window, 'addTab', {
        url: 'min://app/pages/settings/index.html'
      })
    }
  }

  /**
   * 应用菜单（所有平台统一）
   * 注意：某些 role 在非 macOS 平台上可能不被支持，需要提供替代实现
   */
  const appMenu = {
    label: app.name,
    submenu: [
      {
        label: l('appMenuAbout').replace('%n', app.name),
        role: process.platform === 'darwin' ? 'about' : undefined,
        click: process.platform !== 'darwin' ? (item, window) => {
          const info = [
            'Min v' + app.getVersion(),
            'Chromium v' + process.versions.chrome
          ]
          electron.dialog.showMessageBox({
            type: 'info',
            title: l('appMenuAbout').replace('%n', app.name),
            message: info.join('\n'),
            buttons: [l('closeDialog')]
          })
        } : undefined
      },
      { type: 'separator' },
      preferencesAction,
      // Services 菜单仅在 macOS 上显示
      ...(process.platform === 'darwin' ? [{
        label: 'Services',
        role: 'services',
        submenu: []
      }] : []),
      ...(process.platform === 'darwin' ? [{ type: 'separator' }] : []),
      // 隐藏相关功能仅在 macOS 上使用 role，其他平台使用 click
      {
        label: l('appMenuHide').replace('%n', app.name),
        accelerator: 'CmdOrCtrl+H',
        role: process.platform === 'darwin' ? 'hide' : undefined,
        click: process.platform !== 'darwin' ? () => {
          // 非 macOS 平台：最小化所有窗口
          windows.getAll().forEach(win => win.minimize())
        } : undefined
      },
      {
        label: l('appMenuHideOthers'),
        accelerator: 'CmdOrCtrl+Alt+H',
        role: process.platform === 'darwin' ? 'hideothers' : undefined,
        visible: process.platform === 'darwin' // 仅在 macOS 上显示
      },
      {
        label: l('appMenuShowAll'),
        role: process.platform === 'darwin' ? 'unhide' : undefined,
        visible: process.platform === 'darwin' // 仅在 macOS 上显示
      },
      { type: 'separator' },
      quitAction
    ]
  }

  /**
   * 文件菜单
   */
  const fileMenu = {
    label: l('appMenuFile'),
    submenu: [
      ...tabTaskActions,
      { type: 'separator' },
      {
        label: l('appMenuSavePageAs'),
        accelerator: 'CmdOrCtrl+s',
        click: (item, window) => {
          sendIPCToWindow(window, 'saveCurrentPage')
        }
      },
      { type: 'separator' },
      {
        label: l('appMenuPrint'),
        accelerator: 'CmdOrCtrl+p',
        click: (item, window) => {
          sendIPCToWindow(window, 'print')
        }
      }
    ]
  }

  /**
   * 编辑菜单
   */
  const editMenu = {
    label: l('appMenuEdit'),
    submenu: [
      {
        label: l('appMenuUndo'),
        accelerator: 'CmdOrCtrl+Z',
        role: 'undo'
      },
      {
        label: l('appMenuRedo'),
        accelerator: 'Shift+CmdOrCtrl+Z',
        role: 'redo'
      },
      { type: 'separator' },
      {
        label: l('appMenuCut'),
        accelerator: 'CmdOrCtrl+X',
        role: 'cut'
      },
      {
        label: l('appMenuCopy'),
        accelerator: 'CmdOrCtrl+C',
        role: 'copy'
      },
      {
        label: l('appMenuPaste'),
        accelerator: 'CmdOrCtrl+V',
        role: 'paste'
      },
      {
        label: l('appMenuPasteAndMatchStyle'),
        accelerator: 'Shift+CmdOrCtrl+V',
        role: 'pasteAndMatchStyle'
      },
      {
        label: l('appMenuSelectAll'),
        accelerator: 'CmdOrCtrl+A',
        role: 'selectall'
      },
      { type: 'separator' },
      {
        label: l('appMenuFind'),
        accelerator: 'CmdOrCtrl+F',
        click: (item, window) => {
          sendIPCToWindow(window, 'findInPage')
        }
      }
    ]
  }

  /**
   * 视图菜单
   */
  const viewMenu = {
    label: l('appMenuView'),
    submenu: [
      ...personalDataItems,
      { type: 'separator' },
      {
        label: l('appMenuZoomIn'),
        accelerator: 'CmdOrCtrl+Plus',
        click: (item, window) => {
          sendIPCToWindow(window, 'zoomIn')
        }
      },
      // 隐藏项：用于支持不同键盘布局的 = 键
      {
        label: l('appMenuZoomIn'),
        accelerator: 'CmdOrCtrl+=',
        click: (item, window) => {
          sendIPCToWindow(window, 'zoomIn')
        },
        visible: false
      },
      {
        label: l('appMenuZoomOut'),
        accelerator: 'CmdOrCtrl+-',
        click: (item, window) => {
          sendIPCToWindow(window, 'zoomOut')
        }
      },
      // 隐藏项：用于支持数字键盘
      {
        label: l('appMenuZoomIn'),
        accelerator: 'CmdOrCtrl+numadd',
        click: (item, window) => {
          sendIPCToWindow(window, 'zoomIn')
        },
        visible: false
      },
      {
        label: l('appMenuZoomOut'),
        accelerator: 'CmdOrCtrl+numsub',
        click: (item, window) => {
          sendIPCToWindow(window, 'zoomOut')
        },
        visible: false
      },
      {
        label: l('appMenuActualSize'),
        accelerator: 'CmdOrCtrl+0',
        click: (item, window) => {
          sendIPCToWindow(window, 'zoomReset')
        }
      },
      { type: 'separator' },
      {
        label: l('appMenuFocusMode'),
        accelerator: undefined,
        type: 'checkbox',
        checked: false,
        click: (item, window) => {
          if (isFocusMode) {
            isFocusMode = false
            windows.getAll().forEach(win => sendIPCToWindow(win, 'exitFocusMode'))
          } else {
            isFocusMode = true
            windows.getAll().forEach(win => sendIPCToWindow(win, 'enterFocusMode'))
            // 等待标签页隐藏后再显示消息，避免混淆
            setTimeout(() => {
              showFocusModeDialog1()
            }, 16)
          }
        }
      },
      {
        label: l('appMenuFullScreen'),
        accelerator: process.platform === 'darwin' ? 'Ctrl+Command+F' : 'F11',
        role: 'togglefullscreen'
      }
    ]
  }

  /**
   * 开发者菜单
   */
  const developerMenu = {
    label: l('appMenuDeveloper'),
    submenu: [
      {
        label: l('appMenuInspectPage'),
        accelerator: process.platform === 'darwin' ? 'Cmd+Alt+I' : 'Ctrl+Shift+I',
        click: (item, window) => {
          sendIPCToWindow(window, 'inspectPage')
        }
      },
      // 隐藏项：提供 F12 快捷键支持
      {
        label: l('appMenuInspectPage'),
        visible: false,
        accelerator: 'f12',
        click: (item, window) => {
          sendIPCToWindow(window, 'inspectPage')
        }
      }
    ]
  }

  /**
   * 窗口菜单（所有平台统一）
   * 注意：window role 在非 macOS 平台上可能不被支持
   */
  const windowMenu = {
    label: l('appMenuWindow'),
    role: process.platform === 'darwin' ? 'window' : undefined,
    submenu: [
      {
        label: l('appMenuMinimize'),
        accelerator: 'CmdOrCtrl+M',
        role: 'minimize'
      },
      {
        label: l('appMenuClose'),
        accelerator: 'CmdOrCtrl+W',
        click: (item, window) => {
          if (windows.getAll().length > 0 && !windows.getAll().some(win => win.isFocused())) {
            // DevTools 窗口已聚焦，关闭它
            const contents = webContents.getAllWebContents()
            for (let i = 0; i < contents.length; i++) {
              if (contents[i].isDevToolsFocused()) {
                contents[i].closeDevTools()
                return
              }
            }
          }
          // 否则，此事件将在主窗口中处理
        }
      },
      {
        label: l('appMenuAlwaysOnTop'),
        type: 'checkbox',
        checked: settings.get('windowAlwaysOnTop') || false,
        click: (item, window) => {
          windows.getAll().forEach(win => {
            win.setAlwaysOnTop(item.checked)
          })
          settings.set('windowAlwaysOnTop', item.checked)
        }
      },
      { type: 'separator' },
      {
        label: l('appMenuBringToFront'),
        role: process.platform === 'darwin' ? 'front' : undefined,
        click: process.platform !== 'darwin' ? (item, window) => {
          // 非 macOS 平台：将窗口前置
          if (window) {
            window.focus()
            window.show()
          } else {
            // 如果没有指定窗口，前置所有窗口
            windows.getAll().forEach(win => {
              win.focus()
              win.show()
            })
          }
        } : undefined
      }
    ]
  }

  /**
   * 帮助菜单（所有平台统一）
   * 注意：关于项已在应用菜单中，此处不重复添加
   */
  const helpMenu = {
    label: l('appMenuHelp'),
    role: 'help',
    submenu: [
      {
        label: l('appMenuKeyboardShortcuts'),
        click: () => {
          openTabInWindow('https://github.com/minbrowser/min/wiki#keyboard-shortcuts')
        }
      },
      {
        label: l('appMenuReportBug'),
        click: () => {
          openTabInWindow('https://github.com/minbrowser/min/issues/new')
        }
      },
      {
        label: l('appMenuTakeTour'),
        click: () => {
          openTabInWindow('https://minbrowser.github.io/min/tour/')
        }
      },
      {
        label: l('appMenuViewGithub'),
        click: () => {
          openTabInWindow('https://github.com/minbrowser/min')
        }
      }
    ]
  }

  /**
   * Dock 菜单（仅 macOS 平台支持）
   * 注意：这是 macOS 系统特有的功能，需要平台检测
   * 在鸿蒙平台上隐藏"新窗口"选项
   */
  const dockMenuItems = [
    {
      label: l('appMenuNewTab'),
      click: (item, window) => {
        sendIPCToWindow(window, 'addTab')
      }
    },
    {
      label: l('appMenuNewPrivateTab'),
      click: (item, window) => {
        sendIPCToWindow(window, 'addPrivateTab')
      }
    },
    {
      label: l('appMenuNewTask'),
      click: (item, window) => {
        sendIPCToWindow(window, 'addTask')
      }
    }
    // 检测是否为鸿蒙平台，如果是则隐藏"新窗口"菜单项
    // ...(isHarmonyOSPlatform && isHarmonyOSPlatform() ? [] : [
    //   {
    //     label: l('appMenuNewWindow'),
    //     click: () => {
    //       if (isFocusMode) {
    //         showFocusModeDialog2()
    //       } else {
    //         createWindow()
    //       }
    //     }
    //   }
    // ])
  ]

  // 如果不是鸿蒙平台，添加"新窗口"菜单项到 Dock 菜单
  if (isHarmonyOSPlatform && isHarmonyOSPlatform()) {
    // 鸿蒙平台：隐藏"新窗口"菜单项
    console.log('鸿蒙平台：已隐藏 Dock 菜单中的"新窗口"选项')
  } else {
    // 非鸿蒙平台：添加"新窗口"菜单项
    dockMenuItems.push({
      label: l('appMenuNewWindow'),
      click: () => {
        if (isFocusMode) {
          showFocusModeDialog2()
        } else {
          createWindow()
        }
      }
    })
  }

  /**
   * 开发模式下的额外菜单项
   */
  const developmentMenuItems = [
    { type: 'separator' },
    {
      label: l('appMenuReloadBrowser'),
      accelerator: isDevelopmentMode ? 'alt+CmdOrCtrl+R' : undefined,
      click: (item, focusedWindow) => {
        destroyAllViews()
        windows.getAll().forEach(win => win.close())
        createWindow()
      }
    },
    {
      label: l('appMenuInspectBrowser'),
      accelerator: process.platform === 'darwin' ? 'Shift+Cmd+Alt+I' : 'Ctrl+Shift+Alt+I',
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          getWindowWebContents(focusedWindow).toggleDevTools()
        }
      }
    },
    {
      label: 'Inspect Places Service',
      click: (item, focusedWindow) => {
        placesWindow.webContents.openDevTools({ mode: 'detach' })
      }
    }
  ]

  return {
    tabTaskActions,
    personalDataItems,
    quitAction,
    preferencesAction,
    appMenu, // 统一的应用菜单（原 macAppMenu）
    fileMenu,
    editMenu,
    viewMenu,
    developerMenu,
    windowMenu, // 统一的窗口菜单（原 macWindowMenu）
    helpMenu,
    dockMenuItems,
    developmentMenuItems,
    createMenuItem,
    handlers // 保存 handlers 引用供构建器使用
  }
}

